package com.dn.lotte.ui.purchase.fragment;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import com.dn.lotte.R;
import com.dn.lotte.app.GlobalApplication;
import com.dn.lotte.bean.CunModeBean;
import com.dn.lotte.bean.PurchaseDetailGameBean;
import com.dn.lotte.bean.PurchaseDetailTypeBean;
import com.dn.lotte.utils.CommonUtils;
import com.dn.lotte.utils.TestCodeUtils;
import com.easy.common.base.BaseFragment;
import com.easy.common.commonutils.SPUtils;
import com.easy.common.commonutils.StringUtils;
import com.easy.common.commonwidget.RippleView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;

public class PurchaseDSFragment extends BaseFragment {

    @Bind(R.id.tv_show)
    TextView mShowPort;
    @Bind(R.id.etTwo)
    EditText mDSInput;
    @Bind(R.id.ds_linear)
    LinearLayout mDSLinear;
    @Bind(R.id.purchaseNumber)
    TextView mPurchaseNumber;
    @Bind(R.id.purchaseMoney)
    TextView mPurchaseMoney;
    @Bind(R.id.oneBbetting)
    RippleView mOkBetting;

    boolean isFirst = true;//是否是第一次进入
    boolean isRenShi = false; //是否是任式
    boolean isSDZ = false; //是否杀对子
    boolean isDPC = false; //是否是低频彩
    boolean isFG = false; //是否是 以“_”线分割的
    private PurchaseDetailGameBean.TableBean mGameDataBean;
    private String mCPName;
    private String mLid;
    private View mAllFooter; // 倍数 返点调节 布局
    private View mRenshiFooter;//任式 个十 布局
    private String mPoint;
    private String minbonus;
    private String posbonus;
    private String mPlayCode;

    public static PurchaseDSFragment getInstance(PurchaseDetailGameBean.TableBean tableBean, String id, String cpName) {
        PurchaseDSFragment purchaseDSFragment = new PurchaseDSFragment();
        purchaseDSFragment.mGameDataBean = tableBean;
        purchaseDSFragment.mCPName = cpName;
        purchaseDSFragment.mLid = id;
        return purchaseDSFragment;
    }

    protected boolean mIsVisible = false;

    /**
     * `
     * 在这里实现Fragment数据的缓加载.
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            mIsVisible = true;
            onVisible();
        } else {
            mIsVisible = false;
            onInvisible();
        }
    }

    protected void onInvisible() {
    }

    /**
     * 显示时加载数据,需要这样的使用
     * 注意声明 isPrepared，先初始化
     * 生命周期会先执行 setUserVisibleHint 再执行onActivityCreated
     * 在 onActivityCreated 之后第一次显示加载数据，只加载一次
     */
    protected void onVisible() {
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_purchase_ds;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    protected void initView() {
        //展示提示
        if (mCPName.contains("11选5") || mCPName.contains("秒赛车") || mCPName.contains("北京PK10")) {
            mShowPort.setText("每注之间用逗号[,]隔开,号码之间用空格[ ]隔开，不足2位要在前面加0。比如 09。");
        } else {
            mShowPort.setText("请输入投注内容,每注选号请使用逗号,空格或 “ , ” 分隔开。");
        }
        minbonus = mGameDataBean.getMinbonus();
        posbonus = mGameDataBean.getPosbonus();
        mPlayCode = mGameDataBean.getTitle2();
        isRenShiState();
        initRenshiFooter();
        initAllFooter();
        mDSLinear.removeAllViews();
        if (isRenShi)
            //个十百千万 任式脚布局
            mDSLinear.addView(mRenshiFooter);
        mDSLinear.addView(mAllFooter);

        getPayNumber();
    }

    // 获取投注数
    private void getPayNumber() {
        mDSInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String reg = "[\u4e00-\u9fa5]";
                Pattern pat = Pattern.compile(reg);

                Matcher mat = pat.matcher(s.toString());
                String editStr = mat.replaceAll("");
                if (!StringUtils.isContainChinese(editStr)) {
                    String saa = editStr;
                    saa = editStr.replace("\n", " ");
                    editStr = saa;
                    if (mCPName.contains("11选5") || mCPName.contains("北京")) {
                        if (editStr.contains(" ")) {
                            saa = editStr.replace(" ", "_");
                        }
                    } else if (mCPName.contains("赛车")) {
                        if (editStr.contains(" ")) {
                            String ss = editStr.replace(" ", "");
                            saa = ss.replace("0", "");
                        } else {
                            saa = editStr.replace("0", "");
                        }
                    } else {
                        if (saa.contains(" ")) {
                            saa = editStr.replace(" ", ",");
                        } else if (saa.contains(";")) {
                            saa = editStr.replace(";", ",");
                        } else if (saa.contains("；")) {
                            saa = editStr.replace("；", ",");
                        } else if (saa.contains(" ")) {
                            saa = editStr.replace(" ", ",");
                        }
                    }

                    editStr = saa;
                    Log.i("DDD", editStr);
                    mSelectNumber = TestCodeUtils.BetNumerice(mPlayCode, editStr, "", isSDZ);
                    if (mSelectNumber > 0)
                        multipleMoney();

//                    if (mPlayCode != null) {
//                        if (strPos.equals("")) {
//                            moneyNumber = TestCodeUtils.BetNumerice(mPlayCode, editStr, "", mSdz.isChecked());
//                        } else {
//                            moneyNumber = TestCodeUtils.BetNumerice(mPlayCode, editStr, strPos, mSdz.isChecked());
//                        }
//                    } else {
//                        moneyNumber = 0;
//                    }
//
//                    List<String> listStr = Arrays.asList(editStr.split(","));
//                    List<String> newList = new ArrayList(new HashSet(listStr));
//                    List<String> newList1 = new ArrayList(new HashSet(listStr));
//                    if (mPlayCode.equals("R_3HX")) {
//                        for (int i = 0; i < newList1.size(); i++) {
//                            String[] strArrary = TestCodeUtils.getStrArr(newList1.get(i).split(""));
//                            if (strArrary.length == 3) {
//                                if (strArrary[0].equals(strArrary[1]) && strArrary[1].equals(strArrary[2])) {
//                                    newList1.remove(i);
//                                }
//                            }
//                        }
//                    }
//                    newList = newList1;
//                    String[] strArray2 = (String[]) newList.toArray(new String[newList.size()]);
//                    StringBuffer sb = new StringBuffer();
//
//                    for (String s2 : strArray2) {
//                        sb.append(s2 + ",");
//                    }

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private String mModels = "元";//圆角模式
    private double model = 1;
    private String mTimes = "1";// 倍数
    private double mNowPoint;
    private double mFDCha;

    private void initAllFooter() {
        mAllFooter = LayoutInflater.from(getActivity()).inflate(R.layout.purchase_detail_foot, null);
        ImageButton redButton = (ImageButton) mAllFooter.findViewById(R.id.red);//倍数 减
        ImageButton addButton = (ImageButton) mAllFooter.findViewById(R.id.add);//倍数 加
        final EditText foldNumber = (EditText) mAllFooter.findViewById(R.id.number);//倍数

        RadioGroup radioGroup = (RadioGroup) mAllFooter.findViewById(R.id.group);
        RadioButton element = (RadioButton) mAllFooter.findViewById(R.id.element);
        RadioButton angle = (RadioButton) mAllFooter.findViewById(R.id.angle);
        RadioButton points = (RadioButton) mAllFooter.findViewById(R.id.points);
        RadioButton deter = (RadioButton) mAllFooter.findViewById(R.id.deter);

        final TextView mNowBounds = (TextView) mAllFooter.findViewById(R.id.tv_now_bounds);
        final TextView mFD = (TextView) mAllFooter.findViewById(R.id.tv_fd);
        final TextView mBuunds = (TextView) mAllFooter.findViewById(R.id.tv_bounds);
        SeekBar seekBar = (SeekBar) mAllFooter.findViewById(R.id.seekbar);

        /**
         *  倍数调节模式处理过程 ------------start-------------
         */
        foldNumber.setText(mTimes);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int a = Integer.parseInt(foldNumber.getText().toString());
                a = a + 1;
                foldNumber.setText(a + "");
                mTimes = a + "";
            }
        });

        redButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int a = Integer.parseInt(foldNumber.getText().toString());
                if (a == 1) {
                    mTimes = 1 + "";
                } else {
                    a = a - 1;
                    mTimes = a + "";
                }
                foldNumber.setText(a + "");
            }
        });

        foldNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtils.isEmpty(s.toString())) {
//                    number.setText("1");
                    mTimes = "1";
                } else {
                    mTimes = foldNumber.getText().toString();
                }
                setNowMoney(mNowBounds, mFD, mBuunds);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        /**
         *  倍数调节模式处理过程 ------------end-------------
         */

        /**
         *  初始化圆角模式 ------------start-------------
         */
        CunModeBean moneyMode = GlobalApplication.getInstance().getMoneyMode();
        if (moneyMode != null && StringUtils.isEmpty(moneyMode.getMode())) {
            switch (moneyMode.getMode()) {
                case "元":
                    model = 1;
                    element.setChecked(true);
                    break;
                case "角":
                    model = 0.1;
                    angle.setChecked(true);
                    break;
                case "分":
                    model = 0.01;
                    points.setChecked(true);
                    break;
                case "厘":
                    model = 0.001;
                    deter.setChecked(true);
                    break;
            }
        } else {
            model = 1;
            element.setChecked(true);
        }


        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.element:
                        mModels = "元";
                        model = 1;
                        setNowMoney(mNowBounds, mFD, mBuunds);
                        break;
                    case R.id.angle:
                        mModels = "角";
                        model = 0.1;
                        setNowMoney(mNowBounds, mFD, mBuunds);
                        break;
                    case R.id.points:
                        mModels = "分";
                        model = 0.01;
                        setNowMoney(mNowBounds, mFD, mBuunds);
                        break;
                    case R.id.deter:
                        mModels = "厘";
                        model = 0.001;
                        setNowMoney(mNowBounds, mFD, mBuunds);
                        break;
                }
            }
        });
        /**
         *  初始化圆角模式 ------------end-------------
         */

        /**
         *  返点调节处理 ------------start-------------
         */

        mPoint = SPUtils.getSharedStringData(getActivity(), "POINT");
        mFDCha = CommonUtils.sub(Double.parseDouble(mPoint), 14.5);
        final int mPoint = (int) (Double.parseDouble(this.mPoint) * 10) - 120;
        seekBar.setMax(25);
        seekBar.setProgress(25);
        mNowPoint = CommonUtils.div((mPoint - seekBar.getProgress()), 10, 2);
        setNowMoney(mNowBounds, mFD, mBuunds);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mNowPoint = CommonUtils.div((mPoint - progress), 10, 2);
                setNowMoney(mNowBounds, mFD, mBuunds);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        /**
         *  返点调节处理 ------------end-------------
         */

    }

    private double mSingelBounds;

    /**
     * 计算并显示金额
     *
     * @param mNowBounds
     * @param mFD
     * @param mBuunds
     */
    private void setNowMoney(TextView mNowBounds, TextView mFD, TextView mBuunds) {
        mFD.setText(mNowPoint + "");
        DecimalFormat df1 = new DecimalFormat("0");// 格式化小数
        double lastFD = CommonUtils.sub(Double.parseDouble(mPoint), mNowPoint);
        String now = df1.format(1700 + CommonUtils.sub(Double.parseDouble(mPoint), mNowPoint) * 10 * 2);// 返回的是String类型
        mBuunds.setText(now);
        if (mCPName.equals("福彩3D") || mCPName.equals("体彩P3")) {
            if (lastFD == 13.0) {
                lastFD = 11.0;
            }
        }
        //规则 20*返点*系数 + minBonus
        double mul = CommonUtils.mul(20, lastFD);
        double mul2 = CommonUtils.mul(mul, Double.parseDouble(posbonus));
        double add = CommonUtils.add(Double.parseDouble(minbonus), mul2);
        //  * 倍数 * 圆角模式

        double timeModel = CommonUtils.mul(Double.parseDouble(mTimes), model); //倍数*圆角模式
        double nowMoney = CommonUtils.mul(timeModel, add); //金钱数量
        nowMoney = CommonUtils.div(nowMoney, (double) 2, 3);
        mSingelBounds = nowMoney;
        mNowBounds.setText(nowMoney + "");
        multipleMoney();
    }

    private int mSelectNumber = 0;
    private double mAlltotal = 0;

    private void multipleMoney() {
        double timeModel = CommonUtils.mul(Double.parseDouble(mTimes), model); //倍数*圆角模式
        double nowMoney = CommonUtils.mul(mSelectNumber, timeModel); //倍数*圆角模式
        mPurchaseMoney.setText(nowMoney + " 元");
        mPurchaseNumber.setText(mSelectNumber + " 注");
        mAlltotal = nowMoney;
    }

    /**
     * 判断是否是 任四 任三。。。
     */
    private String parentTitle = "";

    /**
     * 任式方案初始化
     */
    private void initRenshiFooter() {
        mRenshiFooter = LayoutInflater.from(getActivity()).inflate(R.layout.foot_detail_rs, null);
        CheckBox cbW = (CheckBox) mRenshiFooter.findViewById(R.id.cb_w);
        CheckBox cbQ = (CheckBox) mRenshiFooter.findViewById(R.id.cb_q);
        CheckBox cbB = (CheckBox) mRenshiFooter.findViewById(R.id.cb_b);
        CheckBox cbS = (CheckBox) mRenshiFooter.findViewById(R.id.cb_s);
        CheckBox cbG = (CheckBox) mRenshiFooter.findViewById(R.id.cb_g);
        final TextView tvNumber = (TextView) mRenshiFooter.findViewById(R.id.tvNumber);
        final List<CheckBox> checkBoxList = new ArrayList<>();
        checkBoxList.add(cbG);
        checkBoxList.add(cbS);
        checkBoxList.add(cbB);
        checkBoxList.add(cbQ);
        checkBoxList.add(cbW);
        //设置默认选项
        if (!StringUtils.isEmpty(parentTitle)) {
            switch (parentTitle) {
                case "任四":
                    setChecked(checkBoxList, 1);
                    break;
                case "任三":
                    setChecked(checkBoxList, 2);
                    break;
                case "任二":
                    setChecked(checkBoxList, 3);
                    break;
            }
        }
        multiplePrecept(parentTitle, checkBoxList, tvNumber);
        cbW.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                multiplePrecept(parentTitle, checkBoxList, tvNumber);
            }
        });
        cbQ.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                multiplePrecept(parentTitle, checkBoxList, tvNumber);
            }
        });
        cbB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                multiplePrecept(parentTitle, checkBoxList, tvNumber);
            }
        });
        cbS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                multiplePrecept(parentTitle, checkBoxList, tvNumber);
            }
        });

        cbG.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                multiplePrecept(parentTitle, checkBoxList, tvNumber);
            }
        });
    }

    private int precept;

    /**
     * 智障方法计算方案数
     *
     * @param parentTitle
     * @param checkBoxList
     * @param tvNumber
     */
    private void multiplePrecept(String parentTitle, List<CheckBox> checkBoxList, TextView tvNumber) {
        List<String> list = new ArrayList<>();
        for (CheckBox checkBox : checkBoxList) {
            if (checkBox.isChecked()) {
                list.add("");
            }
        }
        precept = 0;
        switch (parentTitle) {
            case "任四":
                if (list.size() < 4) {
                    precept = 0;
                }
                if (list.size() == 4) {
                    precept = 1;
                }
                if (list.size() == 5) {
                    precept = 5;
                }
                break;
            case "任三":
                if (list.size() < 3) {
                    precept = 0;
                }
                if (list.size() == 3) {
                    precept = 1;
                }
                if (list.size() == 4) {
                    precept = 4;
                }
                if (list.size() == 5) {
                    precept = 10;
                }
                break;
            case "任二":
                if (list.size() < 2) {
                    precept = 0;
                }
                if (list.size() == 2) {
                    precept = 1;
                }
                if (list.size() == 3) {
                    precept = 3;
                }
                if (list.size() == 4) {
                    precept = 6;
                }
                if (list.size() == 5) {
                    precept = 10;
                }
                break;
        }
        tvNumber.setText("共有 " + precept + " 种方案");
//        returnSelectNumberData(mSelectNumber);
    }

    private void setChecked(List<CheckBox> checkBoxList, int strPos) {
        for (int i = 0; i < checkBoxList.size(); i++) {
            if (i < checkBoxList.size() - strPos) {
                checkBoxList.get(i).setChecked(true);
            } else
                checkBoxList.get(i).setChecked(false);
        }
    }

    /**
     * 判断各种情况
     */
    public void isRenShiState() {
        PurchaseDetailTypeBean gameTypeDataList = CommonUtils.getGameTypeDataList(mLid);
        if (gameTypeDataList != null) {
            List<PurchaseDetailTypeBean.TableBean> titleList = gameTypeDataList.getTable();
            for (PurchaseDetailTypeBean.TableBean bean : titleList) {
                if (mGameDataBean.getRadio().equals(bean.getId())) {

                    if (bean.getTitle().equals("任四") || bean.getTitle().equals("任三") || bean.getTitle().equals("任二")) {
                        parentTitle = bean.getTitle();
                        isRenShi = true;
                    }


                    if (bean.getTitle().equals("前二") || bean.getTitle().equals("后二") || bean.getTitle().equals("任二")) {
                        if (mGameDataBean.getTitle().equals("直选复式") || mGameDataBean.getTitle().equals("直选单式")
                                || mGameDataBean.getTitle().equals("任二复式") || mGameDataBean.getTitle().equals("任二单式"))
                            isSDZ = true;
                    }

                    if (bean.getTitle().equals("五星")) {
                        if (mGameDataBean.getTitle().equals("组选120") || mGameDataBean.getTitle().equals("组选60")
                                || mGameDataBean.getTitle().equals("组选30") || mGameDataBean.getTitle().equals("组选20")
                                || mGameDataBean.getTitle().equals("组选10") || mGameDataBean.getTitle().equals("组选5")) {
                            isFG = true;
                        }
                    }
                    if (bean.getTitle().equals("四星")) {
                        if (mGameDataBean.getTitle().equals("组选12") || mGameDataBean.getTitle().equals("组选6")
                                || mGameDataBean.getTitle().equals("组选4"))
                            isFG = true;
                    }
                    if (bean.getTitle().equals("前三") || bean.getTitle().equals("中三") || bean.getTitle().equals("后三")
                            || bean.getTitle().equals("任三")) {
                        if (mGameDataBean.getTitle().equals("和值尾数") || mGameDataBean.getTitle().equals("组选包胆")
                                || mGameDataBean.getTitle().equals("直选跨度")) {
                            isFG = true;
                        }
                    }

                    if (bean.getTitle().equals("前二") || bean.getTitle().equals("后二") || bean.getTitle().equals("任二")) {
                        if (mGameDataBean.getTitle().equals("组选包胆") || mGameDataBean.getTitle().equals("直选跨度")) {
                            isFG = true;
                        }
                    }
                    if (bean.getTitle().equals("龙虎") || bean.getTitle().equals("趣味")) {
                        isFG = true;
                    }
                }
            }
        }
    }

}
